//
//  UIViewController+Statistical.m
//  Router
//
//  Created by DongSen on 2019/1/8.
//  Copyright © 2019年 董森森. All rights reserved.
//

#import <objc/runtime.h>
#import "Router.h"
#import "UIViewController+Statistical.h"

NSString const * objectKey = @"ds_object";
NSString const * blockKey = @"ds_block";
@implementation UIViewController (Statistical)
@dynamic ds_object;
@dynamic ds_block;

- (id)ds_object{
    return objc_getAssociatedObject(self, &objectKey);
}
- (void)setDs_object:(id)ds_object{
    objc_setAssociatedObject(self, &objectKey, ds_object, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (CallBack)ds_block{
    id block = objc_getAssociatedObject(self, &blockKey);
    return block;
}
- (void)setDs_block:(CallBack)ds_block{
    objc_setAssociatedObject(self, &blockKey, ds_block, OBJC_ASSOCIATION_COPY);
}

- (void)pushTo:(NSString*)name withObject:(id)object callBack:(void(^)(id model))block animation:(BOOL)animation{
    UIViewController * push =  [self className:name];
    if (!push) return;
    if (object!=nil)push.ds_object = object;
    if (block!=nil) push.ds_block = block;
    if (self.navigationController){
        self.navigationController.delegate = [Router share].delegate;
        [self.navigationController pushViewController:push animated:animation];
    }
    else{
        push.transitioningDelegate = [Router share].delegate;
        printf("retain count = %ld\n",CFGetRetainCount((__bridge CFTypeRef)([Router share])));
        [self presentViewController:push animated:animation completion:^{}];
    }
}
- (void)popTo:(NSString*)name withObject:(id)object callBack:(void(^)(id model))block animation:(BOOL)animation{
    if (!name){
        [self.navigationController popViewControllerAnimated:animation];
        return;
    }
    __block UIViewController * pop;
    if (self.navigationController){
        [self.navigationController.viewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([[obj class] isMemberOfClass:[self getClass:name]]){
                pop = obj;
                *stop = YES;
            }
        }];
        if (!pop)
            [self.navigationController popToRootViewControllerAnimated:animation];
        else{
            if (object!=nil)pop.ds_object = object;
            [self.navigationController popToViewController:pop animated:animation];
        }
    }
    else{
        if (self.presentationController)
            [self dismissViewControllerAnimated:animation completion:^{}];
        else{
            pop = [self className:name];
            [self presentViewController:pop animated:animation completion:^{}];
        }
    }
}

- (void)presentTo:(NSString*)name withObject:(id)object callBack:(void(^)(id model))block animation:(BOOL)animation{
    UIViewController * present =  [self className:name];
    if (!present) return;
    if (object!=nil) present.ds_object = object;
    if (block!=nil) present.ds_block  = block;
    present.transitioningDelegate = [Router share].delegate;
    [self presentViewController:present animated:animation completion:^{}];
}


/**
 从配置文件中读取类名
 
 @param name <#name description#>
 @return <#return value description#>
 */
- (NSString*)classFromConfig:(NSString*)name{
    if ([Router share].viewListDic.allKeys.count>0)
        return [[Router share].viewListDic valueForKey:name];//如果没有配置则使用默认的
    else
        return name;
}

/**
 根据类名名称创建类
 
 @param name <#name description#>
 @return return value description
 */
- (Class)getClass:(NSString*)name{
    NSString * relaceName = [self classFromConfig:name];
    const char * cName = [relaceName?relaceName:name cStringUsingEncoding:NSASCIIStringEncoding];
    Class newClass = objc_getClass(cName);
    return newClass;
}
- (UIViewController*)className:(NSString*)name{
    return [[[self getClass:name] alloc] init];
}


+(void)load{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        SEL origselint = @selector(viewDidAppear:);
        
        Method origMethod = class_getInstanceMethod([self class], origselint);
        
        SEL swizselint = @selector(viewAnalusisint:);
        
        Method swizMethod = class_getInstanceMethod([self class],swizselint);
        //
        BOOL addMehtodint = class_addMethod([self class], origselint, method_getImplementation(swizMethod), method_getTypeEncoding(swizMethod));
        if (addMehtodint)
            class_replaceMethod([self class], swizselint, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
        else
            method_exchangeImplementations(origMethod, swizMethod);
        SEL origselout = @selector(viewDidDisappear:);
        Method origMethodOut = class_getInstanceMethod([self class], origselout);
        SEL swizselout = @selector(viewAnalusisout:);
        Method swizMethodout = class_getInstanceMethod([self class],swizselout);
        //
        BOOL addMehtodout = class_addMethod([self class], origselout, method_getImplementation(swizMethodout), method_getTypeEncoding(swizMethodout));
        if (addMehtodout)
            class_replaceMethod([self class], swizselout, method_getImplementation(origMethodOut), method_getTypeEncoding(origMethodOut));
        else
            method_exchangeImplementations(origMethodOut, swizMethodout);
    });
    
}
// 进入页面
- (void)viewAnalusisint:(BOOL)animation{
    if (!([self.class isKindOfClass:[UINavigationController class]]||[self.className isEqualToString:@"UINavigationController"])) {
        NSLog(@"进入页面%@",self.className);
        [[Router share].showArray addObject:[self timeDictionary]];
    }
    [self viewAnalusisint:animation];
}
// 离开页面
- (void)viewAnalusisout:(BOOL)animation{
    if (!([self.class isKindOfClass:[UINavigationController class]]||[self.className isEqualToString:@"UINavigationController"])) {
        NSLog(@"离开页面%@",self.className);
        [[Router share].showArray addObject:[self timeDictionary]];
    }
    [self viewAnalusisout:animation];
}

- (NSDictionary*)timeDictionary{
    NSString *time = [NSString stringWithFormat:@"%lld", (long long)[[NSDate date] timeIntervalSince1970]];
    NSLog(@"%@",self.className);
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setValue:time forKey:@"time"];
    [dic setValue:self.className forKey:@"pageName"];
    if (self.ds_object)
        [dic setObject:self.ds_object forKey:@"object"];
    return dic;
}
- (NSString*)className{
    return [[Router share].viewListDic valueForKey:NSStringFromClass(self.class)]?[[Router share].viewListDic valueForKey:NSStringFromClass(self.class)]:NSStringFromClass(self.class);
}


@end
